package codegen

import (
	"fmt"
	"gitee.com/hxchjm/goge/codegen/utils"
	"gitee.com/hxchjm/goge/codegen/utils/pathx"
	"github.com/siddontang/go/config"
	"path/filepath"
	"strings"
)

const grpcTemplate = `package grpc

import (
	"{{.rootPkg}}/api"

	"go-main/library/conf"
	"go-main/library/net/rpc/warden"
)

// New a grpc server.
func New(svc api.{{.serviceCamelName}}Server) (svr *warden.Server, err error) {
	var cfg warden.ServerConfig
	if err = conf.Bind("grpc", &cfg); err != nil {
		return
	}
	svr = warden.NewServer(&cfg, warden.WithAppId(api.AppID))
	api.Register{{.serviceCamelName}}Server(svr.Server(), svc)
	svr, err = svr.Start()
	return
}

`

func genGrpc(dir, rootPkg string, cfg *config.Config, filename string) error {
	//name := strings.ToLower(api.Service.Name)
	//filename, err := format.FileNamingFormat(cfg.NamingFormat, name)
	//if err != nil {
	//	return err
	//}

	/*	filename := name
		configName := filename
		if strings.HasSuffix(filename, "-api") {
			filename = strings.ReplaceAll(filename, "-api", "")
		}*/
	svrCamelName := utils.SnakeToCamel(filepath.Base(rootPkg))
	return utils.GenFile(utils.FileGenConfig{
		Dir:          dir,
		Subdir:       grpcDir,
		Filename:     filename,
		TemplateName: "mainTemplate",
		//Category:        category,
		//TemplateFile:    mainTemplateFile,
		BuiltinTemplate: grpcTemplate,
		Data: map[string]string{
			"importPackages":   genGrpcImports(rootPkg),
			"rootPkg":          rootPkg,
			"serviceCamelName": svrCamelName,
		},
	})
}

func genGrpcImports(parentPkg string) string {
	var imports []string
	imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, appDir)))
	//imports = append(imports, fmt.Sprintf("\"%s/core/conf\"", vars.ProjectOpenSourceURL))
	//imports = append(imports, fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL))
	return strings.Join(imports, "\n\t")
}
